package com.xy.yunduo.web.interceptor;

import com.xy.yunduo.utils.JsonUtil;
import org.apache.commons.codec.Charsets;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @author dujiuxin
 * @date 2018/5/11
 *
 * 拦截器基类
 *
 */
public abstract class BaseInterceptor extends HandlerInterceptorAdapter {
    /*
    * 获取Controller注解
    * */
    protected <A extends Annotation> A getRequestControllerAnnotation(HandlerMethod handlerMethod, Class<A> annotationClass) throws ClassNotFoundException {
        A annotation= handlerMethod.getBean().getClass().getAnnotation(annotationClass);
        if(annotation==null) {
            String springClassName=handlerMethod.getBean().getClass().getName();
            String className=null;
            if(springClassName.indexOf("$$")>-1)
                className= springClassName.substring(0,springClassName.indexOf("$$"));
            else
                className=springClassName;
            Class action= Class.forName(className);
            if(action!=null&&action.isAnnotationPresent(annotationClass)){
                annotation=(A)action.getAnnotation(annotationClass);
            }
        }
        return annotation;
    }
    /*
    *获取 controller 或 action 注解
    * 首先获取 action 注解 如果存在直接返回，如果不存在 获取controller上注解
    * */
    protected <A extends Annotation> A getRequestAnnotation(Object handler, Class<A> annotationClass) throws ClassNotFoundException {
        if(!(handler instanceof HandlerMethod)){
            return  null;
        }
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        A annotation=handlerMethod.getMethodAnnotation(annotationClass);
        if(annotation==null){
            annotation=  getRequestControllerAnnotation(handlerMethod,annotationClass);
        }
        return annotation;
    }
    /*
    * 向客户端输出 json类型消息
    * */
    protected void responseJson(HttpServletResponse response, Map<String,String> param) throws IOException {
        byte[] bytes= JsonUtil.dump(param).getBytes(Charsets.UTF_8);
        response.setContentLength(bytes.length);
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream out= response.getOutputStream();
        out.write(bytes);
        out.flush();
    }
}
